package com.wangxiaonan.berry.util;

import java.util.Map;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.springframework.util.Assert;

/**
 * @Author: wangxiaonan
 * @Date: 2019/7/3
 **/
public class PoiUtils {

    public static HSSFWorkbook createWorkbook(Map<String, String[][]> sheets, HSSFWorkbook workbook) {
        Assert.notEmpty(sheets, "sheet is null");
        // 1. 初始化 workBook
        if (workbook == null) {
            workbook = new HSSFWorkbook();
        }

        // 2. 初始化sheet，支持多sheet创建
        for (Map.Entry entry : sheets.entrySet()) {
            String sheetName = String.valueOf(entry.getKey());
            String[][] sheetContent = (String[][]) entry.getValue();

            // 创建sheet
            HSSFSheet sheet = workbook.createSheet(sheetName);

            // 设置标题，sheetContent数据的第一行为标题行
            HSSFRow titleRow = sheet.createRow(0);
            // ** title style **
            HSSFCellStyle style = workbook.createCellStyle();
            style.setAlignment(HorizontalAlignment.CENTER);// 居中显示
            for (int i = 0; i < sheetContent[0].length; ++i) {
                HSSFCell cell = titleRow.createCell(i);
                cell.setCellValue(sheetContent[0][i]);
                cell.setCellStyle(style);
            }

            // 设置内容，第一行是标题，从第二行开始
            for (int i = 1; i < sheetContent.length; ++i) {
                HSSFRow row = sheet.createRow(i);
                for (int j = 0; j < sheetContent[i].length; ++j) {
                    row.createCell(j).setCellValue(sheetContent[i][j]);
                }
            }

        }

        // 结束
        return workbook;
    }

}
